﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using NETCore.Encrypt;
using Newtonsoft.Json;
using System;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WucCloud.Application;
using WucCloud.Database;
using WucCloud.Entity;
using WucCloud.Utility;

namespace WucCloud.WebApi.Controllers
{
    /// <summary>
    /// 登录（Token令牌）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [AllowAnonymous]
    public class LoginController : ControllerBase
    {
        /// <summary>
        /// 用户服务类
        /// </summary>
        private readonly UserInfoService _service;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service"></param>
        public LoginController(UserInfoService service)
        {
            _service = service;
        }


        /// <summary>
        /// 登录 (账号密码校验)
        /// </summary>
        /// <param name="accountname">登录账户</param>
        /// <param name="password">登录密码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<UnifyResult>> CheckLogin([Required] string accountname, [Required] string password)
        {
            try
            {
                var result = await _service.CheckSign(accountname, password);

                if (result != null)
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description(),
                        Data = result.ToString()
                    };
                }
                else
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description(),
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                return new UnifyResult<dynamic>
                {
                    StatusCode = ResultCode.Error,
                    Message = ResultCode.Error.Description(),
                    Data = ex.Message.ToString()
                };
            }
        }

        /// <summary>
        /// 微信小程序 登录
        /// </summary>
        /// <param name="js_code">登录时获取的code</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<UnifyResult>> WeChatLogin([Required] string js_code)
        { 
            WeChatRoutine login = new WeChatRoutine();
            login.AppId = "wx46967ae7de71793d";//固定值，小程序AppId
            login.AppSecret = "307bb3c04f25221b56afba835a49d4d3";//固定值，小程序AppSecret
            login.Code = js_code; //不固定 登录时获取的code

            string param = $"?appid={login.AppId}&secret={login.AppSecret}&js_code={login.Code}&grant_type=authorization_code";
            string url = @"https://api.weixin.qq.com/sns/jscode2session" + param;

            var handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip
            };
            using (var http = new HttpClient(handler))
            {
                //await异步等待回应
                var response = await http.GetAsync(url);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                var a = response.StatusCode;

                //await异步读取最后的JSON（注意此时gzip已经被自动解压缩了，因为上面的AutomaticDecompression = DecompressionMethods.GZip）
                string responseContent = await response.Content.ReadAsStringAsync();
                var resultModel = JsonConvert.DeserializeObject<WeChatRoutineResult>(responseContent);

                //将微信当前登录用户唯一标识/会话密钥 写入Session
                if (!string.IsNullOrEmpty(resultModel.OpenId) && !string.IsNullOrEmpty(resultModel.SessionKey))
                {
                    GlobalContext.SetOpenId(resultModel.OpenId);
                    GlobalContext.SetSessionKey(resultModel.SessionKey);
                }
                //操作成功
                if (resultModel != null)
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Success,
                        Message = ResultCode.Success.Description(),
                        Data = resultModel
                    };
                }
                //操作失败
                else
                {
                    return new UnifyResult<dynamic>
                    {
                        StatusCode = ResultCode.Failed,
                        Message = ResultCode.Failed.Description(),
                        Data = null,
                        TotalCount = 0
                    };
                }
            }
        }
    }
}
